import {
  createThesis,
  destoryThesis,
  queryStudentThesisList,
  updateStudentThesis,
} from '@/services/ThesisManage/myThesis/ThesisController';
import { DeleteOutlined, EyeOutlined, ToTopOutlined } from '@ant-design/icons';
import { PageContainer } from '@ant-design/pro-layout';
import ProTable from '@ant-design/pro-table';
import { Button, message, Modal, Popconfirm } from 'antd';
import { useRef } from 'react';
import { history } from 'umi';
import ThesisForm from './components/thesisForm';

const MyThesis = () => {
  // table form逻辑
  const modalFormRef = useRef(null);
  const tableRef = useRef(null);

  const onSubmit = async () => {
    const res = await modalFormRef?.current?.validateFields();
    console.log(res, 'res');
    const values = await modalFormRef?.current?.getFieldsValue();
    const relVal = {
      ...values,
      thesis_url: values.file[0]?.response?.data,
    };
    const thesisRes = await createThesis(relVal);
    if (thesisRes?.code === 200) {
      message.success(res?.message || '创建成功');
      tableRef?.current?.reload();
      return Promise.resolve();
    }
    return Promise.reject();
  };

  const onReupload = async (thesis_id) => {
    const res = await modalFormRef?.current?.validateFields();
    console.log(res, 'res');
    const values = await modalFormRef?.current?.getFieldsValue();
    console.log(values, 'values');
    const relVal = {
      thesis_id: thesis_id,
      ...values,
      thesis_url: values.file[0]?.response?.data,
    };
    delete relVal.thesis_status;
    const thesisRes = await updateStudentThesis(relVal);
    if (thesisRes?.code === 200) {
      message.success(res?.message || '修改成功');
      tableRef?.current?.reload();
      return Promise.resolve();
    }
    return Promise.reject();
  };

  const toDetail = (value) => {
    history.push(`/thesisManage/studentThesis/detail/${value.thesis_id}`);
  };

  const toReupload = (item) => {
    Modal.confirm({
      title: '重新上传',
      width: 600,
      icon: false,
      onOk: () => onReupload(item.thesis_id),
      okText: '保存',
      cancelText: '取消',
      content: <ThesisForm modalFormRef={modalFormRef} cItem={item} />,
    });
  };

  const toDestory = async (value) => {
    const res = await destoryThesis({ thesis_id: value.thesis_id });
    if (res.code === 200) {
      tableRef?.current?.reload();
      message.success('删除成功');
    }
  };

  const onOpenModal = (item) => {
    Modal.confirm({
      title: '新增论文',
      width: 600,
      icon: false,
      onOk: () => onSubmit(item),
      okText: '保存',
      cancelText: '取消',
      content: <ThesisForm modalFormRef={modalFormRef} cItem={item} />,
    });
  };

  const onDel = async (id) => {
    const res = await delUser({ id });
    if (res?.code === 200) {
      message.success(res?.message || '删除成功');
      tableRef?.current?.reloadAndRest?.();
    }
  };

  const columns = [
    {
      title: '论文名称',
      dataIndex: 'thesis_name',
      hideInTable: true,
    },
    {
      title: '教师姓名',
      dataIndex: 'teacher_name',
      hideInTable: true,
    },
    {
      title: '教师工号',
      dataIndex: 'teacher_jsnumber',
      hideInTable: true,
    },
    {
      title: '论文状态',
      dataIndex: 'thesis_status',
      hideInTable: true,
      valueType: 'select',
      valueEnum: new Map([
        ['待审查', '待审查'],
        ['审查中', '审查中'],
        ['已完成', '已完成'],
      ]),
    },
    {
      title: '序号',
      dataIndex: 'id',
      hideInSearch: true,
      width: 60,
      render: (text, record, index) => {
        return index + 1;
      },
    },
    {
      title: '论文名称',
      dataIndex: 'thesis_name',
      hideInSearch: true,
    },
    {
      title: '指导教师姓名',
      dataIndex: 'teacher_thesis',
      hideInSearch: true,
      render: (value, record, index) => {
        return value.name;
      },
    },
    {
      title: '指导教师工号',
      dataIndex: 'teacher_thesis',
      hideInSearch: true,
      render: (value, record, index) => {
        return value.js_number;
      },
    },
    {
      title: '论文状态',
      dataIndex: 'thesis_status',
      hideInSearch: true,
    },
    {
      title: '操作',
      key: 'option',
      valueType: 'option',
      width: 200,
      render: (_, value) =>
        value.thesis_status === '待审查'
          ? [
              <Button
                type="primary"
                title="查看详情"
                key="view"
                shape="circle"
                icon={<EyeOutlined />}
                onClick={() => toDetail(value)}
              />,
              <Popconfirm
                placement="topRight"
                title={'重新上传论文将会清空所有批注！'}
                onConfirm={() => toReupload(value)}
                okText="确定"
                cancelText="取消"
                key="del"
              >
                <Button
                  type="primary"
                  title="重新上传"
                  key="view"
                  shape="circle"
                  icon={<ToTopOutlined />}
                />
              </Popconfirm>,
              <Popconfirm
                placement="topRight"
                title={'删除论文将会清空所有批注！'}
                onConfirm={() => toDestory(value)}
                okText="确定"
                cancelText="取消"
                key="del"
              >
                <Button
                  type="primary"
                  danger
                  key="destory"
                  shape="circle"
                  icon={<DeleteOutlined />}
                />
              </Popconfirm>,
            ]
          : [
              <Button
                type="primary"
                title="查看详情"
                key="view"
                shape="circle"
                icon={<EyeOutlined />}
                onClick={() => toDetail(value)}
              />,
              <Popconfirm
                placement="topRight"
                title={'删除论文将会清空所有批注！'}
                onConfirm={() => toDestory(value)}
                okText="确定"
                cancelText="取消"
                key="del"
              >
                <Button
                  type="primary"
                  title="删除论文"
                  danger
                  key="destory"
                  shape="circle"
                  icon={<DeleteOutlined />}
                />
              </Popconfirm>,
            ],
    },
  ];

  return (
    <PageContainer>
      <ProTable
        actionRef={tableRef}
        bordered
        rowKey="id"
        columns={columns}
        search={{ labelWidth: 'auto' }}
        request={async (params = {}, sort, filter) => {
          console.log(params, sort, filter);
          const { current, pageSize, ...otherParams } = params;
          const res = await queryStudentThesisList({
            current,
            pageSize,
            ...otherParams,
          });
          if (res?.code === 200) {
            return {
              total: res?.data?.count,
              data: res?.data?.rows,
              success: true,
            };
          }
          return {
            success: false,
          };
        }}
        pagination={{
          pageSize: 10,
          showSizeChanger: true,
        }}
        toolBarRender={() => [
          <Button type="primary" key="new" onClick={() => onOpenModal()}>
            新增论文
          </Button>,
        ]}
      />
    </PageContainer>
  );
};

export default MyThesis;
